from prj001.constants import serial_number, today_date

from prj001.models.geninfo import GeneralInfo

from django.db.models import Max

from datetime import date


def define_today():
    serial_today = '{}{}{}'.format(date.today().year,
                                   str(date.today().month).zfill(2),
                                   str(date.today().day).zfill(2))
    # new day
    if not today_date:
        today_date.append(serial_today)

    if serial_today != today_date[0]:
        today_date.clear()
        today_date.append(serial_today)
        serial_number.clear()
        serial_number.append(1)

    return serial_today


def create_serial():

    serial_today = define_today()

    if len(serial_number) <= 9999:
        serial = '%s%04d' % (serial_today, len(serial_number))
    else:
        serial = '%s%05d' % (serial_today, len(serial_number))
    serial_number.append(1)
    return serial


def find_today_max():
    serial_today = define_today()

    info_list = GeneralInfo.objects.filter(serial__icontains=serial_today)

    if not info_list:
        return create_serial()

    serial = info_list.aggregate(Max('serial'))

    len_of_max = len(serial.get('serial__max'))

    if len_of_max in (12, 13):
        if len_of_max == 12:
            max_number = int(serial.get('serial__max')[-4:])
        else:
            max_number = int(serial.get('serial__max')[-5:])

        for i in range(max_number - len(serial_number) + 1):
            serial_number.append(1)

    return create_serial()
